﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;

namespace BookCompanion.SandboxedSolution
{
  [ToolboxItemAttribute(false)]
  public class CitiesListWebPart : WebPart
  {
    public class City
    {
      public String Name { get; set; }
      public String Region { get; set; }
      public String Latitude { get; set; }
      public String Longitude { get; set; }
    }
    
    protected GridView gvCities;

    [WebBrowsable, Personalizable(PersonalizationScope.Shared)]
    public String ListName { get; set; }
    
    protected override void CreateChildControls()
    {
      gvCities = new GridView 
      {
        ID = this.ID + "gvCities",
        AutoGenerateColumns = true,
        Height = Unit.Percentage(100.0),
        Width = Unit.Percentage(100.0)
      };
      this.Controls.Add(gvCities);
    }

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      this.EnsureChildControls();
      if (!String.IsNullOrEmpty(this.ListName))
      {
        SPWeb web = SPContext.Current.Web;
        SPList list = web.Lists[this.ListName];
        SPListItemCollection listItems = list.Items;
        var cities = new List<City>();
        foreach (SPListItem listItem in listItems)
        {
          cities.Add(new City
          {
            Name = listItem["Title"].ToString(),
            Region = listItem["Regione"].ToString(),
            Latitude = listItem["Latitudine"].ToString(),
            Longitude = listItem["Longitudine"].ToString()
          });
        }
        gvCities.DataSource = cities;
        gvCities.DataBind();
      }
    }
  }
}
